package com.filldream.fastboot.common.annotation.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.filldream.fastboot.common.annotation.TmAnn;
import com.filldream.fastboot.common.constant.enums.TmTypeEnum;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import java.io.IOException;
import java.util.Objects;

/**
 * 脱敏序列化
 * @author RickSun
 * @date 2023-11-09
 */
@NoArgsConstructor
@AllArgsConstructor
public class TmSerialize extends JsonSerializer implements ContextualSerializer {

    /** 脱敏注解 **/
    private TmAnn tmAnn;

    @Override
    public void serialize(Object origin, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        String tmResult = TmTypeEnum.tm(tmAnn, origin.toString());
        jsonGenerator.writeString(tmResult);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null) {
            if (Objects.equals(beanProperty.getType().getRawClass(), String.class)) {
                TmAnn tmAnnotation = beanProperty.getAnnotation(TmAnn.class);
                if (tmAnnotation == null) {
                    tmAnnotation = beanProperty.getContextAnnotation(TmAnn.class);
                }
                if (tmAnnotation != null) {
                    return new TmSerialize(tmAnnotation);
                }
            }
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        return serializerProvider.findNullValueSerializer(null);
    }


}
